package meb

import (
	"github.com/gin-gonic/gin"
	"github.com/mosongcc/gotool/gtime"
	"time"
	"vitepress-serve/internal/common/hgin"
	"vitepress-serve/internal/model"
)

// UserInfo 查询用户信息
func (ctl *Controller) UserInfo(ctx *gin.Context) (err error) {
	token := hgin.CtxToken(ctx)

	var user model.User
	if err = ctl.db.Where("uid = ?", token.Uid).Take(&user).Error; err != nil {
		return
	}

	if user.Type == "" {
		user.Type = model.USER_TYPE_USR
	}

	// 如果是会员，判断会员有效期，已过期则修改会员类型
	if user.Type == model.USER_TYPE_VIP {
		if user.VipDate < gtime.NowF8() {
			//会员已过期，改为普通用户
			user.Type = model.USER_TYPE_USR
			user.Mtime = gtime.NowF14()
			if err = ctl.db.Save(&user).Error; err != nil {
				return
			}
		}
		user.VipDate = gtime.ParseT8(user.VipDate).Format(time.DateOnly)
	}

	if user.Type == model.USER_TYPE_USR {
		user.VipDate = ""
	}

	hgin.ApiRes(ctx, &UserInfoBody{
		Uid:      user.Uid,
		Nickname: user.Nickname,
		Avatar:   user.Avatar,
		Ctime:    user.Ctime,
		Type:     user.Type,
		VipDate:  user.VipDate,
	})
	return
}

type UserInfoBody struct {
	Uid      string         `json:"uid"`
	LoginId  string         `json:"login_id,omitempty"`
	Nickname string         `json:"nickname"`
	Avatar   string         `json:"avatar"`
	Ctime    string         `json:"ctime"`
	Type     model.UserType `json:"type"`
	VipDate  string         `json:"vip_date,omitempty"` //会员到期日期 yyyy-MM-dd
}
